package com.interactive.internal.ant;

import java.io.File;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;

public class GenerateVersionMain extends Task
{
    public void execute() throws BuildException
    {
        validateAttributes();

        log("Attempting to generate " + className + ".java in package " + packageName +
                           " for project " + projectName + ", version " + version, Project.MSG_VERBOSE);

        StringBuffer javaCode = InjectionUtils.readResourceFile("VersionInfo.java.txt");

        InjectionUtils.replaceAll(javaCode, "PACKAGE_NAME", packageName);
        InjectionUtils.replaceAll(javaCode, "PROJECT_NAME", projectName);
        InjectionUtils.replaceAll(javaCode, "VERSION", version);
        InjectionUtils.replaceAll(javaCode, "CLASS_NAME", className);
        InjectionUtils.replaceAll(javaCode, "COPYRIGHT_STRING", copyright);
        
        String fileName = sourceDirectory + File.separator +
                          packageName.replace('.', File.separatorChar) +
                          File.separator + className + ".java";
        InjectionUtils.writeFile(fileName, javaCode.toString());

        log("Successfully injected version main.", Project.MSG_VERBOSE);
    }

    // Attribute Access for ANT
    public void setSourceDir(File sourceDirectory) { this.sourceDirectory = sourceDirectory.getAbsolutePath(); }
    private String sourceDirectory;

    public void setPackage(String packageName) { this.packageName = packageName; }
    private String packageName;

    public void setProject(String projectName) { this.projectName = projectName; }
    private String projectName;

    public void setVersion(String version) { this.version = version; }
    private String version;

    public void setClass(String className) { this.className = className; }
    private String className = null;
    
    public void setCopyright(String copyright) { this.copyright = copyright; }
    private String copyright = null;

    private void validateAttributes()
    {
        if (sourceDirectory == null)
            throw new BuildException("You must specify a source directory.");
        if (packageName == null)
            throw new BuildException("You must specify a package.");
        if (projectName == null)
            throw new BuildException("You must specify a project name.");
        if (version == null)
            throw new BuildException("You must specify a version.");
        if (className == null)
        {
            className = "VersionInfo";
            log("Version class not specified: defaulting to \"" + className + "\".", Project.MSG_WARN);
        }
    }
}
